package com.zhangfb95.crosschain.server.infra.config.configuration;

import com.zhangfb95.crosschain.infra.util.tls.server.JettyWebServerBuilder;
import com.zhangfb95.crosschain.infra.util.tls.server.WebServerSslProperties;
import com.zhangfb95.crosschain.server.infra.config.properties.WebServerProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.server.WebServer;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.stereotype.Component;

/**
 * 多个web服务器工厂
 *
 * @author zhangfubing
 * @since 2023/10/17
 */
@Slf4j
@Component
public class MultiServletWebServerFactory implements ServletWebServerFactory {

    @Autowired
    private WebServerProperties webServerProperties;

    @Override
    public WebServer getWebServer(ServletContextInitializer... initializers) {
        MultiWebServer multiWebServer = new MultiWebServer();

        for (WebServerProperties.Host host : webServerProperties.getHosts()) {
            String name = host.getName();
            Integer port = host.getPort();

            WebServerSslProperties sslProperties = new WebServerSslProperties()
                    .setPort(port)
                    .setSslType(host.getSslType())
                    .setCaCert(host.getCaCert())
                    .setSslKey(host.getSslKey())
                    .setSslCert(host.getSslCert());
            WebServer webServer = JettyWebServerBuilder.build(sslProperties, initializers);
            multiWebServer.putWebServer(name, webServer);
        }

        return multiWebServer;
    }
}
